package com.elasticsearchtemplate.dao;


import com.elasticsearchtemplate.entity.Emp;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.intellij.lang.annotations.Language;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 官方文档：https://docs.spring.io/spring-data/elasticsearch/docs/4.3.10/reference/html/#
 */
@Repository
public class EmpElasticTemplateDaoImpl implements EmpElasticTemplateDao {


    @Autowired
    private ElasticsearchRestTemplate template;

    @Override
    public void createIndexAndMapping(String indexName,String mappingJson) {
        template.indexOps(IndexCoordinates.of(indexName))
                .create(new HashMap<>(), Document.parse(mappingJson));
    }

    @Override
    public void insertDocument(String indexName,Emp emp) {
        template.save(emp, IndexCoordinates.of(indexName));
    }

    @Override
    public List<Emp> findAllByName(String indexName,String name) {
        HighlightBuilder highlightBuilder = new HighlightBuilder()
                .field("name")
                .highlighterType("unified")
                .preTags("<span class='hl'>")
                .postTags("</span>");

        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("birthplace", name))
                .withHighlightBuilder(highlightBuilder)
                .build();
        SearchHits<Emp> searchHits = template.search(
                nativeSearchQuery, Emp.class, IndexCoordinates.of(indexName));

        return searchHits.getSearchHits()
                .stream()
                .map(empSearchHit -> empSearchHit.getContent())
                .collect(Collectors.toList());
    }
}
